package com.azt.front.interceptor;

import com.azt.api.enums.LoginTypeEnum;
import com.azt.api.pojo.Role;
import com.azt.api.pojo.User;
import com.azt.api.service.UserService;
import com.azt.front.model.LoginCookie;
import com.azt.front.service.UserFrontService;
import com.azt.front.utils.ContextUtil;
import com.azt.front.utils.SpringContextUtil;
import com.azt.front.utils.UserContext;
import com.azt.model.FrontGlobals;
import com.xiaoleilu.hutool.util.CollectionUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

import static com.azt.front.utils.ContextUtil.getLoginCookie;

/**
 * 记住我拦截器（获取记住我cookie，将其载入session中实现自动登录）
 * Created by shangwq on 2016/8/7.
 */
public class RememberMeInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private UserService userService;

    @Autowired
    private UserFrontService userFrontService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取cookie
        LoginCookie cookie = getLoginCookie();;
        if(!ContextUtil.isLogined() && cookie != null) {
            User user = userService.getUserByUserName(cookie.getUsername());
            if(user != null && user.getId().equals(cookie.getUserId()) && StrUtil.equals(user.getSalt(), cookie.getSalt())) {
                userFrontService.recordLoginSession(user, LoginTypeEnum.REMEMBERME.getValue(), cookie.getCurrentRoleId());
            }
        }

        User _user = (User) request.getSession().getAttribute(FrontGlobals.CURRENT_USER);
        if(_user != null) {
            User user = SpringContextUtil.getBean(UserService.class).getFullUserById(_user.getId());
            //将user信息注入UserContext中
            UserContext.setUser(user);
            request.getSession().setAttribute(FrontGlobals.CURRENT_USER, user);
            
            //加入freemarker共享变量，以便所有页面均可访问
            //freeMarkerConfig.getConfiguration().setSharedVariable("currUser", user);

            Role role = (Role) request.getSession().getAttribute(FrontGlobals.CURRENT_ROLE);
            Role currentRole = null;
            List<Role> roles = user.getRoles();
            if (CollectionUtil.isNotEmpty(roles) && role != null) {
                for (Role _role : roles) {
                    if (_role.getRoleType().equals(role.getRoleType())) {
                        currentRole = _role;
                        break;
                    }
                }
            }
            if (currentRole == null && CollectionUtil.isNotEmpty(roles)) {
                currentRole = roles.get(0);
            }
            request.getSession().setAttribute(FrontGlobals.CURRENT_ROLE, currentRole);


            if(cookie != null && currentRole != null) {
                if(ContextUtil.getLoginType().intValue() == LoginTypeEnum.AUTH.getValue()) {
                    // 没有自动登录的时候，更改currentrRoleId
                    LoginCookie newCookie = new LoginCookie(cookie.getUserId(), cookie.getUsername(),
                            currentRole.getId(), user.getSalt(), cookie.getLoginTime(), cookie.getExpireTime());
                    ContextUtil.setLoginCookie(newCookie);
                } else if(ContextUtil.getLoginType().intValue() == LoginTypeEnum.REMEMBERME.getValue()) {
                    // 自动登录的时候，cookie自动续期
                    ContextUtil.setRememberMeLoginCookie(cookie.getUserId(), cookie.getUsername(), currentRole.getId(), user.getSalt());
                }
            }
        } else {
            UserContext.clear();
        }
        return true;
    }
}